from twisted.internet import task
from mudpyl.ui.cli_color import colored
from mudpyl.matchers import match
from sys import stdout

class TextUI:

    def __init__(self,realm,logfile=None):
        if not logfile:
            logfile=open('.log','w')
        self.logfile=logfile
        self.nonFirst=True
        self.realm=realm
        self._input=''
        
        realm.aliases.append(self.quit)

        realm.add_protocol(self)

        print 'TextUI init done'

    def metalineReceived(self,metaline):

        if metaline.fores[0].name=='ORANGE' :
            return

        line=metaline.line

        out=''

        for num,s in enumerate(line):


            color=metaline.fores.get_color_at(num)

            out=out+colored( text=s,color=(color,None) )

        self.logfile.write(line)

        stdout.write(out)

        
    def close(self):
        self.logfile.close()

    def connectionLost(self):
        pass

    def connectionMade(self):
        self._task=task.LoopingCall(self.input_)

        self._task.start(0.005)

    def submit_line(self):
        self.realm.receive_ui_line(self._input)

    def input_(self):

        import sys
        import select

        reader,out,error=select.select([sys.stdin],[],[],0.005)

        if not reader :
            return

        s=reader[0].readline()

        self._input+=s

        if self._input[-1]=='\n':

            self.submit_line()
            self._input=''

    @match(r'^#quit$')
    def quit(match,realm):

        realm.root.quit()

reactor_install = None

configure=TextUI
